import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class LibraryGUI extends JFrame {
    private JTextField titleField, authorField, isbnField;
    private JTextArea outputArea;
    private JButton addButton, borrowButton, returnButton, displayButton;
    private JComboBox<String> libraryCombo;
    private JComboBox<String> actionCombo;

    private static Connection connection;

    public LibraryGUI() {
        super("Library Management System");
        initializeDatabase();
        createUI();
    }

    private void initializeDatabase() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/library_db", "root", "password");

            // Create books table if not exists
            Statement stmt = connection.createStatement();
            stmt.execute("CREATE TABLE IF NOT EXISTS books (" +
                    "id INT AUTO_INCREMENT PRIMARY KEY, " +
                    "title VARCHAR(100) NOT NULL, " +
                    "author VARCHAR(100), " +
                    "isbn VARCHAR(20), " +
                    "entry_date DATE, " +
                    "is_rented BOOLEAN DEFAULT false, " +
                    "borrowed_date DATE, " +
                    "returned_date DATE, " +
                    "library_name VARCHAR(50))");
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "Database connection failed: " + e.getMessage());
        }
    }

    private void createUI() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(600, 500);
        setLayout(new BorderLayout());

        // Input panel
        JPanel inputPanel = new JPanel(new GridLayout(6, 2, 5, 5));

        inputPanel.add(new JLabel("Title:"));
        titleField = new JTextField();
        inputPanel.add(titleField);

        inputPanel.add(new JLabel("Author:"));
        authorField = new JTextField();
        inputPanel.add(authorField);

        inputPanel.add(new JLabel("ISBN:"));
        isbnField = new JTextField();
        inputPanel.add(isbnField);

        inputPanel.add(new JLabel("Library:"));
        libraryCombo = new JComboBox<>(new String[]{"Main Library", "Liberty Library"});
        inputPanel.add(libraryCombo);

        inputPanel.add(new JLabel("Action:"));
        actionCombo = new JComboBox<>(new String[]{"Add Book", "Borrow Book", "Return Book"});
        inputPanel.add(actionCombo);

        addButton = new JButton("Execute");
        addButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                executeAction();
            }
        });
        inputPanel.add(addButton);

        add(inputPanel, BorderLayout.NORTH);

        // Output area
        outputArea = new JTextArea();
        outputArea.setEditable(false);
        add(new JScrollPane(outputArea), BorderLayout.CENTER);

        // Display button
        displayButton = new JButton("Display All Books");
        displayButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                displayAllBooks();
            }
        });
        add(displayButton, BorderLayout.SOUTH);

        setVisible(true);
    }

    private void executeAction() {
        String title = titleField.getText().trim();
        String author = authorField.getText().trim();
        String isbn = isbnField.getText().trim();
        String library = (String)libraryCombo.getSelectedItem();
        String action = (String)actionCombo.getSelectedItem();

        if (title.isEmpty()) {
            JOptionPane.showMessageDialog(this, "Title cannot be empty");
            return;
        }

        try {
            switch (action) {
                case "Add Book":
                    addBookToDatabase(title, author, isbn, library);
                    break;
                case "Borrow Book":
                    borrowBook(title, library);
                    break;
                case "Return Book":
                    returnBook(title, library);
                    break;
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "Database error: " + ex.getMessage());
        }
    }

    private void addBookToDatabase(String title, String author, String isbn, String library) throws SQLException {
        String sql = "INSERT INTO books (title, author, isbn, entry_date, library_name) VALUES (?, ?, ?, ?, ?)";
        PreparedStatement pstmt = connection.prepareStatement(sql);
        pstmt.setString(1, title);
        pstmt.setString(2, author);
        pstmt.setString(3, isbn);
        pstmt.setDate(4, new java.sql.Date(new Date().getTime()));
        pstmt.setString(5, library);

        int rows = pstmt.executeUpdate();
        if (rows > 0) {
            outputArea.append("Book added successfully: " + title + "\n");
        }
    }

    private void borrowBook(String title, String library) throws SQLException {
        // Check if book exists and is available
        String checkSql = "SELECT is_rented FROM books WHERE title = ? AND library_name = ?";
        PreparedStatement checkStmt = connection.prepareStatement(checkSql);
        checkStmt.setString(1, title);
        checkStmt.setString(2, library);
        ResultSet rs = checkStmt.executeQuery();

        if (rs.next()) {
            boolean isRented = rs.getBoolean("is_rented");
            if (isRented) {
                outputArea.append("Sorry, '" + title + "' is already borrowed.\n");
            } else {
                // Update to mark as borrowed
                String updateSql = "UPDATE books SET is_rented = true, borrowed_date = ? WHERE title = ? AND library_name = ?";
                PreparedStatement updateStmt = connection.prepareStatement(updateSql);
                updateStmt.setDate(1, new java.sql.Date(new Date().getTime()));
                updateStmt.setString(2, title);
                updateStmt.setString(3, library);

                int rows = updateStmt.executeUpdate();
                if (rows > 0) {
                    outputArea.append("You successfully borrowed '" + title + "'\n");
                }
            }
        } else {
            outputArea.append("Sorry, '" + title + "' is not in our catalog.\n");
        }
    }

    private void returnBook(String title, String library) throws SQLException {
        // Check if book exists and is borrowed
        String checkSql = "SELECT is_rented FROM books WHERE title = ? AND library_name = ?";
        PreparedStatement checkStmt = connection.prepareStatement(checkSql);
        checkStmt.setString(1, title);
        checkStmt.setString(2, library);
        ResultSet rs = checkStmt.executeQuery();

        if (rs.next()) {
            boolean isRented = rs.getBoolean("is_rented");
            if (!isRented) {
                outputArea.append("This book is not currently borrowed.\n");
            } else {
                // Update to mark as returned
                String updateSql = "UPDATE books SET is_rented = false, returned_date = ? WHERE title = ? AND library_name = ?";
                PreparedStatement updateStmt = connection.prepareStatement(updateSql);
                updateStmt.setDate(1, new java.sql.Date(new Date().getTime()));
                updateStmt.setString(2, title);
                updateStmt.setString(3, library);

                int rows = updateStmt.executeUpdate();
                if (rows > 0) {
                    outputArea.append("You successfully returned '" + title + "'\n");
                }
            }
        } else {
            outputArea.append("This book is not from our library.\n");
        }
    }

    private void displayAllBooks() {
        outputArea.setText(""); // Clear output

        try {
            String sql = "SELECT title, author, isbn, is_rented, library_name FROM books ORDER BY library_name, title";
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery(sql);

            String currentLibrary = "";
            boolean firstRow = true;

            while (rs.next()) {
                String library = rs.getString("library_name");
                if (!library.equals(currentLibrary)) {
                    if (!firstRow) {
                        outputArea.append("\n");
                    }
                    outputArea.append("Books in " + library + ":\n");
                    currentLibrary = library;
                    firstRow = false;
                }

                String title = rs.getString("title");
                String author = rs.getString("author");
                String isbn = rs.getString("isbn");
                boolean isRented = rs.getBoolean("is_rented");

                outputArea.append("- " + title);
                if (author != null && !author.isEmpty()) {
                    outputArea.append(" by " + author);
                }
                if (isbn != null && !isbn.isEmpty()) {
                    outputArea.append(" (ISBN: " + isbn + ")");
                }
                outputArea.append(" - " + (isRented ? "Borrowed" : "Available") + "\n");
            }

            if (firstRow) {
                outputArea.append("No books in the database.\n");
            }
        } catch (SQLException ex) {
            outputArea.append("Error retrieving books: " + ex.getMessage() + "\n");
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new LibraryGUI();
            }
        });
    }

    // Close connection when program exits
    static {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                try {
                    if (connection != null && !connection.isClosed()) {
                        connection.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}